#include "auto_feed.h"

#if (COMPLIE_AUTO_FEED == 1)

void scale_device_thread(void *param)
{
  user_device_t servo = cc_device_get(devices, CC_DEVICE_TYPE_SERVO, 1);
  user_device_t scale = cc_device_get(devices, CC_DEVICE_TYPE_SCALE, 1);
  if (servo == CC_NULL || scale == CC_NULL)
  {
    cc_log("device is null\r\n");
    cc_thread_delete_by_cb(scale_device_thread);
  }
  cc_port_t scale_port = cc_port_init(CC_PORT_AUTO_FEED_SCALE, "feed_scale", 10, 50);
  cc_port_set_state(scale_port, CC_PORT_STATE_CONN);
  int food_full_flag = 0;
  while (1)
  {
    float weight;
    scale->read_cb(scale, CC_NULL, CC_SCALE_READ_GRAM, &weight);
    cc_log_d("now weight(%.2f)\r\n", weight);
    if (weight > setting_weight)
    {
      if (food_full_flag != 1)
      {
        cc_log("weight(%.2f) is bigger than %.2f,close servo\r\n", weight, setting_weight);
        food_full_flag = 1;
        cc_mnode_t node = cc_port_get_msg_node(scale_port, 1000);
        sprintf((char *)node->mem, "servo_close");
        cc_port_publish(scale_port, "servo_ctrl", node);
      }
    }
    else
    {
      food_full_flag = 0;
    }
    cc_delay(10);
  }
}
CC_THREAD_REGISTER(scale_device_thread, 12, 3096);

#endif